/**
 * @file util index
 * @description util index
 * @author fanxueliang<fanxueliang
 */

import {SpecAttrConfigType} from '../interface';
import {map, includes, set, isObject} from 'lodash-es';
import {CustomObject} from '@jsw/report-core';

// 索引匹配中括号的正则
export const keyReg = /^\[(.*)\]$/;

export const formatKey = (key: string) => {
    const matchResult = keyReg.exec(key);
    if (matchResult) {
        return matchResult[1];
    }
    return key;
};

// 是否为嵌套层级的字符串
export const isNestedString = (key: string): boolean => key.includes('.');

export const setNoRewriteAttrs = (configList: SpecAttrConfigType[], noRewriteAttrs: string[]) => {
    return map(configList, (it) => {
        if (includes(noRewriteAttrs, it.path)) {
            set(it, 'attr.disabled', true);
        }
        return it;
    });
};

export function safeParseJSON(data: string | CustomObject | CustomObject[], defaultVal: any) {
    if (isObject(data)) {
        return data;
    }
    try {
        const ret = JSON.parse(data);
        if (ret === null) {
            return defaultVal || {};
        }
        return ret;
    } catch (e) {
        return defaultVal || {};
    }
}
